(function() {
    'use strict';
    var commonObject = function() {
        //自定义换行正则
        this.regWarp = /<br\/>/g;
        //图标配置
        this.iconList=[
            [   "sign-in","user","user-plus","suitcase","bell","bell-o","diamond","lock","unlock-alt","unlock",
                "bookmark","bookmark-o","object-group","cog","building","building-o","desktop","map-marker","key","refresh",
                "university","coffee","check-circle-o","location-arrow","feed ","fire","lightbulb-o","mail-reply-all","mail-forward","mail-reply",
                "book","calendar","close","check","clone","clock-o","code","edit","eye","filter",
            ],
            [   "power-off","phone","phone-square","paper-plane","qrcode","question-circle","recycle","retweet","search","rocket",
                "folder","folder-o","search-plus","gears","legal","pencil","pencil-square-o","paper-plane-o","motorcycle","music",
                "share-square","car","random","share-square-o","share-alt-square","share-alt","sign-out","signal","sitemap","line-chart",
                "space-shuttle","star","star-o","tablet","street-view","tachometer","tag","tags","taxi","television"
            ],
            [   "times-circle","times-circle-o","tint","trash-o","trophy","umbrella","tv","wifi","wrench","video-camera",
                "plane ","bitcoin","ils","cny","dollar","eur","money","gbp","gg","inr",
                "ruble","chain-broken","dedent","link","font","repeat","rotate-left","rotate-right","th-large","eject",
                "fast-backward","fast-forward","compass","forward","backward","arrow-down","arrow-left","arrow-right","arrow-up","pause",
            ]
        ];
        //用户方面
        this.userInfoPath='/agent-sys/admin/user/getDetail.do';
        this.threeLinkageData;
        this.agentSysCacheWord='agent_sys_loginData';
        //经纪人管理
        this.agentListPort="/agent-sys/admin/agentInfo/index.do";
        this.agentInfoPort="/agent-sys/admin/agentInfo/getDetail.do";
        this.agentAuthPort="/agent-sys/admin/agentInfo/auth.do";
        this.agentUpdatePort="/agent-sys/admin/agentInfo/update.do";
        this.delTVPanelInfoPort="/agent-sys/admin/agentInfo/checkPerfectAgentInfo.do";
        //公司管理
        this.companyListPort="/agent-sys/admin/companyInfo/index.do";
        this.companyInfoPort="/agent-sys/admin/companyInfo/getDetail.do";
        this.companyUpdatePort="/agent-sys/admin/companyInfo/update.do";
        this.companyAddPort="/agent-sys/admin/companyInfo/save.do";
        //门店管理
        this.storeListPort="/agent-sys/admin/storeInfo/getStoreList.do";
        this.storeInfoPort="/agent-sys/admin/storeInfo/getDetail.do";
        this.storeUpdatePort="/agent-sys/admin/storeInfo/update.do";
        this.storeAddPort="/agent-sys/admin/storeInfo/save.do";
        //经纪人报房管理
        this.collectHouseListPort="/agent-sys/admin/agentHouseInfo/getHouseList.do";
        this.collectHouseInfoPort="/agent-sys/admin/agentHouseInfo/getDetail.do";
        this.collectHouseUpdatePort="/agent-sys/admin/agentHouseInfo/update.do";
        //配置
        this.getSystemConfPath="/agent-sys/admin/systemConf/getByParamKey.do";
        this.setSystemConfPath="/agent-sys/admin/systemConf/setByParamKey.do";
        //舍艺房源
        this.esheyiHouseListPath="/agent-sys/admin/houseInfo/index.do";
        this.esheyiHouseInfoPath="/agent-sys/admin/houseInfo/getDetail.do";
        this.esheyiHouseUpdatePath="/agent-sys/admin/houseInfo/update.do";
        this.esheyiHouseSavePath="/agent-sys/admin/houseInfo/save.do";
        //房源音频接口
        this.uploadAudioPath = "/uploadFileSave.do";
        this.uploadAudioCoverPhotoPath = "/agent-sys/admin/houseInfo/addAudioCover.do";
        this.audioListPath = "/agent-sys/admin/audioInfo/getAudioList.do";
        this.audioDetailPath = "/agent-sys/admin/audioInfo/getDetail.do";
        this.audioSortPath = "/agent-sys/admin/audioInfo/updateSort.do";
        this.addAudioPath = "/agent-sys/admin/audioInfo/saveAudio.do";
        this.delAudioPath = "/agent-sys/admin/audioInfo/batchDelete.do";
        this.updateAudioPath = "/agent-sys/admin/audioInfo/update.do";
        this.changeAudioStatusPath = "/agent-sys/admin/audioInfo/updateStatus.do";
        //悬赏房源
        this.rewardHouseListPath="/agent-sys/admin/rewardInfo/getRewardList.do";
        this.rewardInfoPath="/agent-sys/admin/rewardInfo/getDetail.do";
        this.rewardInfoUpdatePath="/agent-sys/admin/rewardInfo/update.do";
        this.rewardStatusUpdatePath="/agent-sys/admin/rewardInfo/updateRewardStatus.do";
        this.StartRewardPath="/agent-sys/admin/rewardInfo/startReward.do";
        //查看记录
        this.visitRecordList="/agent-sys/admin/rewardViewInfo/getRewardViewList.do";
        //推荐房源
        this.recommendHousePath="/agent-sys/admin/rewardInfo/recommend.do";
        //图片上传接口
        this.uploadImagePort='/agent-sys/admin/upload/uploadFile.do';
        //菜单管理
        this.menuListPath='/agent-sys/admin/menu/index.do';
        this.menuInfoPath='/agent-sys/admin/menu/getDetail.do';
        this.addMenuPath='/agent-sys/admin/menu/save.do';
        this.updateMenuPath='/agent-sys/admin/menu/update.do';
        //参数设置
        this.sysParamConfListPath='/agent-sys/admin/systemConf/index.do';
        this.sysParamConfInfoPath='/agent-sys/admin/systemConf/getDetail.do';
        this.updatesysParamConfPath='/agent-sys/admin/systemConf/update.do';
        this.addSysParamConfPath='/agent-sys/admin/systemConf/save.do';
        this.deleteSysParamConfPath='/agent-sys/admin/systemConf/batchDelete.do';
        //申请装锁
        this.addLockPath='/agent-sys/admin/houseInfo/addLock.do';
        this.removeLockPath='/agent-sys/admin/houseInfo/removeLock.do';
        this.syncHouseLockPath='/agent-sys/admin/houseInfo/getLock.do';//同步安装信息
        //门锁
        this.lockListPath='/agent-sys/admin/lockInfo/getLockList.do';
        this.easyOpenPath='/agent-sys/admin/lockInfo/openLock.do';
        this.syncLockInfoPath='/agent-sys/admin/lockInfo/updateLock.do';//同步锁电量和在线
        this.setlockPwdPath='/agent-sys/admin/lockInfo/setLockPassword.do';//设置密码
        //开锁记录
        this.lockRecordListPath='/agent-sys/admin/lockOpenInfo/index.do';
        // 积分规则配置
        this.creditRuleListPath='/agent-sys/admin/pointRuleInfo/getRuleInfoList.do';
        this.creditRuleUpdatePath='/agent-sys/admin/pointRuleInfo/update.do';
        // 悬赏房源的带看记录管理
        this.houseVisitedRecordListPath='/agent-sys/admin/houseVisitInfo/getHouseVisitList.do';
        this.houseVisitedVerifyPath='/agent-sys/admin/houseVisitInfo/verifyHouseVisit.do';
        this.houseVisitedInfoPath='/agent-sys/admin/houseVisitInfo/getDetail.do';
        //经纪人积分管理
        this.allCreditListPath='/agent-sys/admin/pointInfo/getPointInfoList.do';
        this.agentCreditRecordListPath='/agent-sys/admin/pointChangeLog/getPointChangeLogList.do';
        //经纪人提现管理
        this.agentGetMoneyByCreditListPath='/agent-sys/admin/pointExchangeInfo/getPointExchangeInfoList.do';
        this.agentGetMoneyByCreditDetailPath='/agent-sys/admin/pointExchangeInfo/getDetail.do';
        this.agentGetMoneyByCreditUpdatePath='/agent-sys/admin/pointExchangeInfo/updateExchangeStatus.do';
        //banner管理
        this.bannerListPath='/agent-sys/admin/bannerInfo/getBannerList.do';
        this.bannerDetailPath='/agent-sys/admin/bannerInfo/getDetail.do';
        this.addBannerPath='/agent-sys/admin/bannerInfo/save.do';
        this.updateBannerPath='/agent-sys/admin/bannerInfo/update.do';
        this.delBannerPath='/agent-sys/admin/bannerInfo/batchDelete.do';
    };
    commonObject.prototype = {
        updateLock:function (options) {
            var self=this;
            var confirmMsg=options.confirmMsg;
            var path=options.path;
            var sendData=options.sendData;
            var listPanel=options.listPanel;
            self.confirm({msg:confirmMsg}).then(function() {
                if(path){
                    $.post(window.globalHost + path, sendData).success(function (data) {
                        if (typeof data == "string") {
                            data = JSON.parse(data);
                        }
                        layer.alert(data.res.msg);
                        listPanel.fnClearTable();
                    });
                }
            });
        },
        /**
         * 上传方法
         * @param {Object} options 上传选项
         * @param {String} options.url 上传url
         * @param {String} [options.paramName=file] 上传文件的param名
         * @param {Number} [options.maxFiles=100] 最大文件数
         * @param {Number} [options.maxFileSize=10] 单文件最大容量，单位MB
         * @param {String} [options.type=image] 上传类型，目前直接受image和file，影响上传控件可接受的文件
         * @param {Object} options.fileFolder 前端文件路径
         * @param {Function} [options.success=undefined] 文件上传后的回调函数
         * @param {Function} [ok] 确定按钮后的callback
         * @param {Function} [cancel] 关闭按钮后的callback
         */
        upload: function(options, ok, cancel) {
            if (!layer) {
                alert("请引入layer插件。");
                return;
            }
            if (!!options === false || !!options.url === false) {
                throw new Error("请定义上传路径")
            }
            return layer.open({
                type: 2,
                title: '文件上传',
                fix: false,
                shadeClose: true,
                area: ['700px', '500px'],
                content: './modal/upload.html',
                btn: ['上传', '关闭'],
                success: function(layerDocument, index) {
                    layerDocument.find("iframe")[0].contentWindow.initDropZone(options);
                },
                yes: function(index, layerDocument) {
                    layerDocument.find("iframe")[0].contentWindow.dropzoneUpload();
                    if (ok) {
                        ok();
                    }
                },
                btn2: cancel
            });
        },
        /**
         * 公共方法，打开新增dialog
         * options 参数
         * url : dialog 打开的页面路径 -- 必填
         * title : 打开的弹框的标题 -- 必填
         * area : 弹框的宽度、高度。默认：['800px', '500px']
         * btn :弹框上面的操作按钮。默认：['保存', '取消']
         * sAjaxSource : 选填，如果填写之后，会把弹出框里面form表单的数据自动提交
         * @param  {[type]} options [description]
         * @return {[type]}         [description]
         */
        openInsertDialog: function(options) {
            var self = this,
                index;
            if (!layer) {
                alert("请引入layer插件。");
            }
            if (!options.url) {
                layer.alert("url 不能为空！");
            }
            if (!options.title) {
                layer.alert("title 不能为空！");
            }
            index = layer.open({
                type: options.type||2,
                title: options.title,
                fix: false,
                maxmin: true,
                shadeClose: true,
                area: !options.area ? ['800px', '500px'] : options.area,
                content: options.url,
                btn: !options.btn ? ['保存', '取消'] : options.btn,
                yes: function(index, layerDocument) {
                    var dialogDocument = layerDocument.find("iframe")[0].contentDocument;
                    var form = dialogDocument.getElementsByTagName("form");
                    var dialogWindow = layerDocument.find("iframe")[0].contentWindow;
                    // var sendData=self.formToJson(form);
                    // console.log(sendData);
                    if (!dialogWindow.formObject.valid()) {
                        return false;
                    }
                    var sendData=self.formToJson(form);
                    var msg="";
                    if(sendData.hasOwnProperty("coverPhoto")){
                        msg=!!sendData.coverPhoto?"":"封面图片";
                        if(!!msg){
                            layer.alert(msg+"必须上传");
                            return false;
                        }
                    }
                    if(sendData.hasOwnProperty("housePhotos")){
                        msg=!!sendData.housePhotos?"":"房源图片";
                        if(!!msg){
                            layer.alert(msg+"必须上传");
                            return false;
                        }
                    }
                    if(sendData.hasOwnProperty("picturePath")){
                        msg=!!sendData.picturePath?"":"banner图片";
                        if(!!msg){
                            layer.alert(msg+"必须上传");
                            return false;
                        }
                    }
                    if (!!options.sAjaxSource) {
                        self.post(options.sAjaxSource, sendData).done(function(record) {
                            layer.alert(record.res.msg);
                            options.ok(record);
                            layer.close(index);
                        }).fail(function(record) {
                            if(options.cancel){
                                options.cancel(record);
                            }
                            // layer.close(index);
                        });
                    } else {
                        options.ok(self.formToJson(form));
                    }
                },
                btn2: options.cancel,
                btn3: options.other
            });
        },
        openTempDialog:function (options) {
            var self = this,
                index;
            if (!layer) {
                alert("请引入layer插件。");
            }
            if (!options.content) {
                layer.alert("content 不能为空！");
            }
            if (!options.title) {
                layer.alert("title 不能为空！");
            }
            var flag=true;
            index=layer.open({
                type: options.type||1,
                title: options.title,
                fix: false,
                maxmin: true,
                shadeClose: true,
                area: !options.area ? ['360px', '160px'] : options.area,
                btn: !options.btn ? ['确定', '取消'] : options.btn,
                content:options.content||options.url||"无内容",
                success:function (layerDocument) {
                    !!options.contentOnLoad && $.isFunction(options.contentOnLoad) && options.contentOnLoad(layerDocument)
                },
                yes: function(index,layerDocument) {
                    if(!!(options.beforeSend && $.isFunction(options.beforeSend)) && !!(options.beforeSend(layerDocument))){
                        if(!!options.ajaxUrl && !!options.sendData){
                            if(flag){
                                $.post(options.ajaxUrl,options.sendData).success(function (data) {
                                    layer.alert(data.res.msg);
                                    var record=self.transformData(data);
                                    if(record.code=="0"){
                                        layer.close(index);
                                        !!options.resOk && $.isFunction(options.resOk) && options.resOk(layerDocument,record);
                                        return false;
                                    }else if(record.code!="0"){
                                        flag=true;
                                    }
                                }).error(function (x,h,r) {
                                    flag=true;
                                });
                            }
                            flag=false;
                        }
                    }else{
                        !!options.FailedMsg?layer.alert(options.FailedMsg):null;
                    }
                },
                btn2: options.cancel
            });
        },
        toUtf8:function (str) {
            var out, i, len, c;
            out = "";
            len = str.length;
            for(i = 0; i < len; i++) {
                c = str.charCodeAt(i);
                if ((c >= 0x0001) && (c <= 0x007F)) {
                    out += str.charAt(i);
                } else if (c > 0x07FF) {
                    out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                    out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));
                    out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
                } else {
                    out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));
                    out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));
                }
            }
            return out;
        },
        getToken: function() {
            var loginData = this.getLocalData(common.agentSysCacheWord);
            if (!loginData) {
                window.location.href = './login.html';
            }
            if (!loginData.token) {
                window.location.href = './login.html';
            }
            return loginData.token;
        },
        setLocalStorage: function(key, value) {
            if (window.localStorage) {
                localStorage.setItem(key, value);
            }
        },
        setSessionStorage: function(key, value) {
            if (window.sessionStorage) {
                sessionStorage.setItem(key, value);
            }
        },
        setCookie: function(key, value, daysToLive) {
            var cookie = key + '=' + encodeURIComponent(value);
            if (typeof daysToLive == 'number') {
                cookie += ';max-age=' + (daysToLive * 60 * 60 * 24);
            }
            document.cookie = cookie;
        },
        getLocalData: function(key) {
            if (window.localStorage) {
                var data = localStorage.getItem(key);
                data = JSON.parse(data);
                return data;
            }
        },
        getSessionData: function(key) {
            if (window.sessionStorage) {
                var data = sessionStorage.getItem(key);
                data = JSON.parse(data);
                return data;
            }
        },
        getCookie: function(key) {},
        compactList:function (list,key,isDeleteKey) {
            //参数Key是冗余字段，用来判断过滤去重
            var result = [];
            var hasIn = function (obj) {
                var b = false;
                result.map(function (item) {
                    if (item[key] == obj[key]) { b = true; }
                });
                return b;
            };
            list.map(function (obj) {
                if (!hasIn(obj)) {
                    result.push(obj);
                }
            });
            //清除冗余字段的属性
            if(!!isDeleteKey){
                result=result.map(function (obj) {
                    delete obj[key];
                    return obj;
                });
            }
            return result;
        },
        /**
         * common 公共的ajax post 提交方法。
         * @param  {[type]} url  [description]
         * @param  {[type]} data [description]
         * @param {Boolean} [showErrorMsg=true] 是否显示错误信息
         * @return {[type]}      [description]
         */
        post: function(url, data, showErrorMsg) {
            if (showErrorMsg === undefined) showErrorMsg = true;
            var dtd = $.Deferred();
            $.post(url, data).success(function(record) {
                if ("1" == record.code) {
                    if (showErrorMsg)
                        layer.alert(record.res.msg);
                    dtd.reject();
                } else {
                    dtd.resolve(record);
                }
            });
            return dtd.promise();
        },
        formToJson: function(selector) {
            var $everyNamedList= $(selector).find("[name]");
            var json={};
            var arr;
            // var radios=$(selector).find("input[type='radio']");
            // var checkBoxVal=[];
            $.each($everyNamedList,function (idx, ele) {
                var $ele=$(ele);
                var everyName=ele.name;
                var everyType=ele.type;
                // var evertValue=ele.value.trim().replace(/[\r\n]/g, "##br##");
                var evertValue=ele.value.trim();
                if(everyType=="radio"){
                    if(!json.hasOwnProperty(everyName)){
                        json[everyName]="";
                    }
                    if(ele.checked){
                        json[everyName]=evertValue;
                    }
                }else if(everyType=="checkbox"){
                    if(!json.hasOwnProperty(everyName)){
                        json[everyName]="";
                        arr=[];
                    }
                    if(ele.checked){
                        arr.push(evertValue);
                        json[everyName]=arr.join(",");
                    }
                }else{
                    if (!json[everyName]) {
                        json[everyName] =evertValue;
                    } else {
                        json[everyName] = json[everyName] + ',' + evertValue;
                    }
                }
            });
            return json;
        },
        /**
         * 把获取到的list数据转换出来
         * @return {[type]} [description]
         */
        transformData: function(record, showErrorMsg) {
            if(typeof record ==="string"){
                record=JSON.parse(record);
            }
            if (showErrorMsg === undefined) showErrorMsg = true;
            if (record.code && record.code !== "0") {
                if (showErrorMsg)
                    layer.alert(record.res.msg);
                return {};
            } else {
                return !!record.res.data ? (record.res.data.record?record.res.data.record:(record.res.data)) : record;
            }
        },
        /**
         * 省市区3级联动
         * @param  {[type]} level1 [description]
         * @param  {[type]} level2 [description]
         * @param  {[type]} level3 [description]
         * @return {[type]}        [description]
         */
        threeLinkage: function(level1, level2, level3) {
            var self = this,
                selectorLevel1 = level1,
                selectorLevel2 = level2,
                selectorLevel3 = level3;

            if (!self.threeLinkageData) {
                self.post(window.globalHost + '/agent-sys/admin/zoneInfo/getZoneInfoOption.do', { status: 'AVAILABLE' }).done(function(data) {
                    self.threeLinkageData = self.transformData(data)[0]['subZone'];
                    lv1(self.threeLinkageData);
                });
            }
            /**
             * 省份
             * @param  {[type]} data [description]
             * @return {[type]}      [description]
             */
            function lv1(data) {
                var list = ['<option value="">请选择省份...</option>'],
                    level1Data = data;
                $.each(data, function(i, I) {
                    list.push('<option value=' + I.id + '>' + I.zoneName + '</option>');
                });
                $(selectorLevel1).html(list.join(""));
                $(selectorLevel1).chosen({}).off('change').on('change', function(ev, obj) {
                    var selectedIndex = ev.currentTarget.selectedIndex;
                    /**
                     * 下标需要减一，因为select初始化的时候最上面有个空的option标签
                     */

                    selectedIndex--;

                    if (!!level1Data.length) {
                        lv2(level1Data[selectedIndex]['subZone']);
                    } else {
                        lv2([]);
                    }
                });
                // if (!!level1Data.length) {
                //     lv2(level1Data[0]['subZone']);
                // } else {
                lv2([]);
                // }

            }

            /**
             * 城市
             * @param  {[type]} data [description]
             * @return {[type]}      [description]
             */
            function lv2(data) {
                var list = ['<option value="">请选择城市...</option>'],
                    level2Data = data;
                // $(selectorLevel2).chosen("destroy").html("");
                if (!!$(selectorLevel2).data('chosen')) {
                    $(selectorLevel2).data('chosen').destroy();
                }
                $.each(data, function(i, I) {
                    list.push('<option value=' + I.id + '>' + I.zoneName + '</option>');
                });
                $(selectorLevel2).html(list.join(""));
                $(selectorLevel2).chosen().off('change').on('change', function(ev, obj) {
                    var selectedIndex = ev.currentTarget.selectedIndex;
                    /**
                     * 下标需要减一，因为select初始化的时候最上面有个空的option标签
                     */

                    selectedIndex--;
                    /**
                     * 区域渲染
                     */

                    if (!!level2Data.length) {
                        lv3(level2Data[selectedIndex]['subZone']);
                    } else {
                        lv3([]);
                    }
                });
                // if (!!level2Data.length) {
                //     lv3(level2Data[0]['subZone']);
                // } else {
                lv3([]);
                // }
            }

            /**
             * 区域
             * @param  {[type]} data [description]
             * @return {[type]}      [description]
             */
            function lv3(data) {
                var list = ['<option value="">请选择区域...</option>'],
                    level3Data = data;
                // $(selectorLevel3).chosen("destroy").html("");
                if (!!$(selectorLevel3).data('chosen')) {
                    $(selectorLevel3).data('chosen').destroy();
                }
                $.each(data, function(i, I) {
                    list.push('<option value=' + I.id + '>' + I.zoneName + '</option>');
                });
                $(selectorLevel3).html(list.join(""));
                $(selectorLevel3).chosen().off('change').on('change', function(ev, obj) {
                    // var selectedIndex = ev.currentTarget.selectedIndex;
                    /**
                     * 下标需要减一，因为select初始化的时候最上面有个空的option标签
                     */
                    // selectedIndex--;
                    // lv3(level3Data[selectedIndex]['subZone']);
                });
            }
        },
        /**
         * 省市区、板块 四级联动
         * @param {[type]} level1 [省份 选择器]  必传
         * @param {[type]} level2 [城市 选择器]  必传
         * @param {[type]} level3 [区域 选择器]  必传
         * @param {[type]} level4 [板块 选择器]  必传
         * @param {[type]} checkedData [回填数据对象]  选填
         */
        FourLinkage: function(level1, level2, level3, level4, checkedData) {
            var self = this,
                selectorLevel1 = level1,
                selectorLevel2 = level2,
                selectorLevel3 = level3,
                selectorLevel4 = level4,
                $houseVillageName=$("#houseVillageName"),
                provinceWord="",
                cityWord="";

            /**
             * 和3级联动同一个数据源
             * @param  {[type]} !self.threeLinkageData [description]
             * @return {[type]}                        [description]
             */
            if (!self.threeLinkageData) {
                self.post(window.globalHost + '/agent-sys/admin/zoneInfo/index.do', { status: 'AVAILABLE' }).done(function(data) {
                    self.threeLinkageData = self.transformData(data)[0]['subZone'];
                    lv1(self.threeLinkageData);
                });
            } else {
                lv1(self.threeLinkageData);
            }

            /**
             * 省份
             * @param  {[type]} data [description]
             * @return {[type]}      [description]
             */
            function lv1(data) {
                var list = ['<option value="">请选择省份...</option>'],
                    level1Data = data,
                    nextLevelData = [];
                $.each(data, function(i, I) {
                    if (!!checkedData && checkedData.lv1 == I.id) {
                        nextLevelData = level1Data[i]['subZone'];
                        list.push('<option selected value=' + I.id + '>' + I.zoneName + '</option>');
                    } else {
                        list.push('<option value=' + I.id + '>' + I.zoneName + '</option>');
                    }
                });
                $(selectorLevel1).html(list.join(""));
                $(selectorLevel1).chosen({}).off('change').on('change', function(ev, obj) {
                    var currentZoneId=$(ev.currentTarget).val();
                    var selectedIndex = ev.currentTarget.selectedIndex;
                    /**
                     * 下标需要减一，因为select初始化的时候最上面有个空的option标签
                     */

                    selectedIndex--;

                    if (!!level1Data.length) {
                        !!level1Data[selectedIndex] && !!level1Data[selectedIndex]['subZone'] ? lv2(level1Data[selectedIndex]['subZone']) : lv2([]);
                        // lv2(level1Data[selectedIndex]['subZone']);
                    } else {
                        lv2([]);
                    }
                    !!$houseVillageName.length?$houseVillageName.val(""):null;
                    if(!!window.myMap){
                        if(!currentZoneId){
                            myMap.getPositionByBaiDuApi({
                                cityName:"上海"
                            });
                        }
                        var currentText=$(this).find(":selected").text();
                        provinceWord=currentText;
                        myMap.getPositionByBaiDuApi({
                            cityName:provinceWord
                        });
                    }
                });
                lv2(nextLevelData);
            }

            /**
             * 城市
             * @param  {[type]} data [description]
             * @return {[type]}      [description]
             */
            function lv2(data) {
                var list = ['<option value="">请选择城市...</option>'],
                    level2Data = data,
                    nextLevelData = [];
                // $(selectorLevel2).chosen("destroy").html("");
                if (!!$(selectorLevel2).data('chosen')) {
                    $(selectorLevel2).data('chosen').destroy();
                }
                $.each(data, function(i, I) {
                    // list.push('<option value=' + I.id + '>' + I.zoneName + '</option>');
                    if (!!checkedData && checkedData.lv2 == I.id) {
                        nextLevelData = level2Data[i]['subZone'];
                        list.push('<option selected value=' + I.id + '>' + I.zoneName + '</option>');
                    } else {
                        list.push('<option value=' + I.id + '>' + I.zoneName + '</option>');
                    }
                });
                $(selectorLevel2).html(list.join(""));
                $(selectorLevel2).chosen().off('change').on('change', function(ev, obj) {
                    var selectedIndex = ev.currentTarget.selectedIndex;
                    var currentZoneId=$(ev.currentTarget).val();
                    /**
                     * 下标需要减一，因为select初始化的时候最上面有个空的option标签
                     */

                    selectedIndex--;
                    /**
                     * 区域渲染
                     */

                    if (!!level2Data.length) {
                        !!level2Data[selectedIndex] && !!level2Data[selectedIndex]['subZone'] ? lv3(level2Data[selectedIndex]['subZone']) : lv3([]);
                        // lv3(level2Data[selectedIndex]['subZone']);
                    } else {
                        lv3([]);
                    }
                    !!$houseVillageName.length?$houseVillageName.val(""):null;
                    if(!!window.myMap){
                        if(!currentZoneId){
                            myMap.getPositionByBaiDuApi({
                                cityName:provinceWord
                            });
                        }
                        var currentText=$(this).find(":selected").text();
                        cityWord=currentText;
                        myMap.getPositionByBaiDuApi({
                            cityName:provinceWord+cityWord
                        });

                    }
                });
                lv3(nextLevelData);
            }

            /**
             * 区域
             * @param  {[type]} data [description]
             * @return {[type]}      [description]
             */
            function lv3(data) {
                var list = ['<option value="">请选择区域...</option>'],
                    level3Data = data,
                    nextLevelData = [];
                // $(selectorLevel3).chosen("destroy").html("");
                if (!!$(selectorLevel3).data('chosen')) {
                    $(selectorLevel3).data('chosen').destroy();
                }
                $.each(data, function(i, I) {
                    // list.push('<option value=' + I.id + '>' + I.zoneName + '</option>');
                    if (!!checkedData && checkedData.lv3 == I.id) {
                        nextLevelData = level3Data[i]['subZone'];
                        list.push('<option selected value=' + I.id + '>' + I.zoneName + '</option>');
                    } else {
                        list.push('<option value=' + I.id + '>' + I.zoneName + '</option>');
                    }
                });
                $(selectorLevel3).html(list.join(""));
                $(selectorLevel3).chosen().off('change').on('change', function(ev, obj) {
                    var selectedIndex = ev.currentTarget.selectedIndex;
                    /**
                     * 下标需要减一，因为select初始化的时候最上面有个空的option标签
                     */
                    selectedIndex--;

                    if (!!level3Data.length) {
                        !!level3Data[selectedIndex] && !!level3Data[selectedIndex]['subZone'] ? lv4(level3Data[selectedIndex]['subZone']) : lv4([]);
                        // lv4(level3Data[selectedIndex]['subZone']);
                    } else {
                        lv3([]);
                    }
                });
                lv4(nextLevelData);
            }

            /**
             * 板块
             * @param  {[type]} data [description]
             * @return {[type]}      [description]
             */
            function lv4(data) {
                var list = ['<option value="">请选择板块...</option>'],
                    level4Data = data;
                if (!!$(selectorLevel4).data('chosen')) {
                    $(selectorLevel4).data('chosen').destroy();
                }
                $.each(data, function(i, I) {
                    // list.push('<option value=' + I.id + '>' + I.zoneName + '</option>');
                    if (!!checkedData && checkedData.lv4 == I.id) {
                        list.push('<option selected value=' + I.id + '>' + I.zoneName + '</option>');
                    } else {
                        list.push('<option value=' + I.id + '>' + I.zoneName + '</option>');
                    }
                });
                $(selectorLevel4).html(list.join(""));
                $(selectorLevel4).chosen().off('change').on('change', function(ev, obj) {

                });
                !!checkedData && !!checkedData.callback && checkedData.callback();
            }
        },
        /**
         * 创建一个空的chosen
         * @param  {String} selector [选择器]
         */
        buildInitSelect:function(selector){
            $(selector).html('<option value="">请选择...</option>');
            $(selector).chosen({});
        },
        /**
         * 基于枚举数据的下拉插件
         * @param  {[type]} selector [选择器]
         * @param  {[type]} data     [数据源]
         * @param  {[type]} checked    [选中的key值]
         * @return {[type]}          [null]
         */
        buildNormalEnumSelect: function(selector, data, checked) {
            var list = ['<option value="">请选择...</option>'];
            var $selector= $(selector);
            if(!!data){
                $.each(data, function(i, I) {
                    if (!!checked && checked == i) {
                        list.push('<option selected value="' + i + '">' + I + '</option>');
                    } else {
                        list.push('<option value="' + i + '">' + I + '</option>');
                    }
                });
            }
            $selector.html(list.join(""));
            $selector.chosen({});
        },
        buildNormalSelect: function(opt) {
            var list = ['<option value="">请选择...</option>'];
            var key=opt.key;
            var txt=opt.text;
            var $selector= $(opt.selector);
            if(!!opt.data && opt.data.length){
                $.each(opt.data, function(i, I) {
                    if (!!opt.checked && opt.checked == I[key]) {
                        list.push('<option selected value="' + I[key] + '">' + I[txt] + '</option>');
                    } else {
                        list.push('<option value="' + I[key] + '">' + I[txt] + '</option>');
                    }
                });
            }
            $selector.html(list.join(""));
            $selector.chosen({});
        },
        /**
         * 基于ajax后台数据源的下拉插件
         * @param  {[type]} options      [参数]
         * @return {[type]}               [null]
         */
        buildNormalAjaxSelect: function(options) {
            var self = this;
            var selector=$(options.selector);

            $.post(options.url, options.data).success(function(data) {
                var data = self.transformData(data);
                var dataList=[];
                var list = ['<option value="">请选择...</option>'];
                $.each(data, function(i, I) {
                    if (!!options.checked && options.checked == I[options.key]) {
                        list.push('<option selected value="' + I[options.key] + '" data-mobile="'+I[options.mobile]+'">' + I[options.value] + '</option>');
                    } else {
                        list.push('<option value="' + I[options.key] + '" data-mobile="'+I[options.mobile]+'">' + I[options.value] + '</option>');
                    }

                });
                selector.html(list.join(""));
                selector.chosen({});
                selector.off("change").on("change",function (e) {
                    var $this=$(this);
                    options.callback($this);
                });
            });
        },
        /**
         * 基于ajax后台数据源的联动下拉插件,部门职务关联
         * @param  {Object} options      [参数]
         *      options.selector : 父级列表选择器
         *      options.selector2 : 子级列表选择器
         *      options.url : ajax请求的数据接口
         *      options.data : ajax请求时发送的数据
         *      options.fatherId : 父级列表项的id
         *      options.fatherChecked : 父级列表内初始化被选中的项
         *      options.fatherValue : 父级列表项的中文值
         *      options.sonKey : 子级列表数据的匹配字段
         *      options.sonId : 子级列表项的id
         *      options.sonChecked : 子级列表内初始化被选中的项
         *      options.sonValue : 子级列表项的中文值
         * @return {[type]}               [null]
         */
        buildLinkedAjaxSelect: function(options) {
            var self = this;
            $.post(options.url, options.data).success(function(data) {
                data = self.transformData(data);
                var lev1List = ['<option value="">请选择...</option>'];
                var lv2ListInit=['<option value="">请选择...</option>'];
                var lv2DataInit=[];
                $.each(data, function(i, I) {
                    if (!!options.fatherChecked && options.fatherChecked == I[options.fatherId]) {
                        lev1List.push('<option selected value="' + I[options.fatherId] + '">' + I[options.fatherValue] + '</option>');
                        lv2DataInit=I[options.sonKey];
                    } else {
                        lev1List.push('<option value="' + I[options.fatherId] + '">' + I[options.fatherValue] + '</option>');
                    }
                });
                if(!!lv2DataInit.length){
                    $.each(lv2DataInit,function (i,I) {
                        if (!!options.sonChecked && options.sonChecked == I[options.sonId]) {
                            lv2ListInit.push('<option selected value="' + I[options.sonId] + '">' + I[options.sonValue] + '</option>');
                        } else {
                            lv2ListInit.push('<option value="' + I[options.sonId] + '">' + I[options.sonValue] + '</option>');
                        }
                    });
                }
                //获取父级列表元素
                var fatherSelector=$(options.fatherSelector);
                //预留父级列表变化的方法
                var fatherSelectorChange=options.fatherSelectorChange;
                //获取子级列表元素
                var sonSelector=$(options.sonSelector);
                //初始化父级和子级下拉列表数据
                // sonSelector.attr("disabled",true);
                fatherSelector.html(lev1List.join(""));
                fatherSelector.chosen({});
                sonSelector.html(lv2ListInit.join(""));
                sonSelector.chosen({});
                //监控父级列表的选择事件，如果父级列表选择变化，那么子级列表状态变成可选择
                fatherSelector.off("change").on("change",function () {
                    // sonSelector.attr("disabled",false);
                    var $this=$(this);
                    var lev2ListTemp = ['<option value="">请选择...</option>'];
                    sonSelector.chosen("destroy");
                    var currentId=$this.val();
                    var dataLev2={};
                    $.each(data,function (i,I) {
                        if(I.id==currentId){
                            dataLev2=I["roles"];
                        }
                    });
                    $.each(dataLev2,function (i, I) {
                        lev2ListTemp.push('<option value="' + I['roleId'] + '">' + I['roleName'] + '</option>');
                    });
                    sonSelector.html(lev2ListTemp.join(""));
                    sonSelector.chosen({});
                    !!fatherSelectorChange && $.isFunction(fatherSelectorChange) && fatherSelectorChange($this,sonSelector);
                });

            });
        },
        /**
         * 根据“name”获取地址栏中的参数
         * @param  {[type]} name [description]
         * @return {[type]}      [description]
         */
        getQueryString: function(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]);
            return null;
        },
        /**
         * 初始化所有的input 输入框，根据name
         * @param  {[type]} jsonObject [description]
         * @return {[type]}            [description]
         */
        initInputByName: function(jsonObject) {
            var self = this;
            for (var p in jsonObject) {
                var input=$("input[name='" + p + "']");
                var inputType=input.attr("type");
                if(inputType!="radio" && inputType!="checkbox"){
                    input.val(jsonObject[p]);
                }
                $("textarea[name='" + p + "']").val(jsonObject[p].toString().replace(self.regWarp,'\r'));
                // $("textarea[name='" + p + "']").val(jsonObject[p].toString());
            }
        },
        initDivById:function (jsonObject) {
            for (var k in jsonObject) {
                var every=$("#"+k);
                if(every.length){
                    every.html(jsonObject[k]);
                }else{
                    continue;
                }
            }
        },
        initInputByNameOnLayer: function(jsonObject,selector) {
            var self = this;
            selector=$(selector);
            for (var p in jsonObject) {
                var input=selector.find(("input[name='" + p + "']"));
                var inputType=input.attr("type");
                if(inputType!="radio" && inputType!="checkbox"){
                    input.val(jsonObject[p]);
                }
                selector.find("textarea[name='" + p + "']").val(jsonObject[p].toString().replace(self.regWarp,'\r'));
            }
        },
        initDivByIdOnLayer:function (jsonObject,selector) {
            selector=$(selector);
            for (var k in jsonObject) {
                var every=selector.find("#"+k);
                if(every.length){
                    every.html(jsonObject[k]);
                }else{
                    continue;
                }
            }
        },
        /**
         * 初始化所有的checkbox 复选框
         * @param  {[type]} selector [选择器]
         * @param {[type]} checkedData [选中的checkbox值]
         */
        getCheckboxChecked: function(selector, checkedData) {
            var checkboxes = $(selector).find('input[type=checkbox]');
            //修正和初始化checkbox的值
            $.each(checkboxes, function() {
                var lv = $(this).next().text();
                $(this).attr('value', lv);
            });
            //遍历数据,选中状态
            if (!!checkedData) {
                var checkedDatas = $.isArray(checkedData) ? checkedData : checkedData.split(',');
                for (var i = 0; i < checkedDatas.length; i++) {
                    $.each(checkboxes, function() {
                        if ($(this).val() === checkedDatas[i]) {
                            $(this).attr('checked', true);
                        }
                    });
                }
            }
        },
        getRadioChecked: function(name, checkedData) {
            var radios=$("input[name='"+name+"']:radio");
            $.each(radios,function (idx, ele) {
                if(ele.value==checkedData){
                    ele.checked=true;
                    return;
                }
            })
        },
        /**
         * 获取日期format，因后端只接收YYYY-MM-DD HH:mm:ss的完整数据格式
         * @param {String} dateStr 日期字符串
         * @param {Boolean} endOfDay 是否为23:59:59.默认为00:00:00
         */
        getFormatedDate: function(dateStr, endOfDay){
            if(endOfDay===undefined || typeof endOfDay!=="boolean"){
                endOfDay=false;
            }
            
            if(window.moment){
                if(endOfDay){
                    return moment(dateStr).endOf("day").format("YYYY-MM-DD HH:mm:ss")
                }else{
                    return moment(dateStr).format("YYYY-MM-DD HH:mm:ss")
                }
            }else{
                if(endOfDay){
                    return dateStr+" 23:59:59";
                }else{
                    return dateStr+" 00:00:00";
                }
            }
        },

         /* 通过layer弹出确认框
         * @param {Object} options 选项
         * @param {String} options.msg 提示信息
         * @param {String} [options.okText=确定]
         * @param {String} [options.cancelText=取消]
         */
        confirm: function(options){
            if (!layer) {
                alert("请引入layer插件。");
                return;
            }
            if(options===undefined){
                throw new Error("options cannot be empty.")
            }
            options.okText= options.okText || "确定";
            options.cancelText=options.cancelText || "取消";
            var dfd = $.Deferred();
            var index = layer.confirm(options.msg,
                {btn:[options.okText,options.cancelText]},
                function(){
                    dfd.resolve(true);
                    layer.close(index);
                },function(){
                    dfd.reject(false);
                });
            return dfd.promise();
        },
        deleteConfirm:function(deleteFunc){
            this.confirm({msg:"确定删除吗？"}).then(deleteFunc);
        },
        changeConfirm:function (msg,changeFunc) {
            this.confirm({msg:msg}).then(changeFunc);
        },
        //decode html encoding, like &#40;("(")
        decodeHTML:function(html){
            return $("<textarea>").val(html).val();
        },
        /**
         * 获取datatable搜索数据
         * @param {String} searchFromSelector 搜索form的选择器
         * @param {Array} aoData datatables回调自带的参数
         * @param {Array} [additionalSearchData] 额外的搜索条件，不由form提供
         */
        getSearchData:function(searchFromSelector,aoData,additionalSearchData){
            var searchData=$(searchFromSelector).serializeArray();
            var dataArr;
            var that=this;
            if($.isArray(additionalSearchData)){
                dataArr=searchData.concat(additionalSearchData);
            }else if($.isPlainObject(additionalSearchData)){
                searchData.push(additionalSearchData);
                dataArr=searchData;
            }else{
                dataArr=searchData;
            }
            //aoData给标准Array加了一个额外属性，导致不能单纯concat
            $.each(dataArr, function (index, item) {
                //后台必须接收包含时分秒的信息，所以需要format日期格式
                if(that.isValidDateString(item.value)){
                    //如果字段包含end dateEnd
                    if(item.name.indexOf("dateStart")>-1){
                        item.value=that.getFormatedDate(item.value);
                    }else if(item.name.indexOf("dateEnd")>-1){
                        item.value=that.getFormatedDate(item.value,true);
                    }
                }
                return aoData.push({
                    'name': item.name,
                    'value': item.value
                });
            });
            return aoData;
        },
        isValidDateString:function(dateStr){
            return !isNaN(Date.parse(dateStr));
        },
        createQRCode:function (selector,link,isBase64) {
            var self = this;
            link=common.toUtf8(link);
            selector.qrcode({
                id:'myCanvas',
                render:'canvas',
                width:600,
                height:600,
                text:link
            });
            var canvas=selector.find("canvas")[0];
            var base64=canvas.toDataURL("image/jpeg",0.98);
            if(!!isBase64){
                return base64;
            }else {
                var blob = self.dataURLtoBlob(base64);
                var url = URL.createObjectURL(blob);
                return url;
            }
        },
        dataURLtoBlob:function (dataurl) {
            var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {type:mime});
        }
    };
    window.common = new commonObject();
}).call(this);
